package com.hitrust.gs.action.productTiptopStock;

import java.io.IOException;
import java.io.InputStream;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.struts.upload.FormFile;

import com.hitrust.gs.business.GSProductTiptopStockProcesser;
import com.hitrust.gs.dao.GSProductStorageDao;

import com.hitrust.gs.form.GSImportExcelForm;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.service.GSBaseAction;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.util.RegulaUtil;
import com.hitrust.gs.util.exception.GSException;
/**
 * 批量导入指定库存产品查询
 * @author wzh
 *
 */
public class ProductStorageShowExeclAction extends GSBaseAction {


	public static final String SHEET_NAME = "产品信息";
	public static final String SEP = "%";
	public static String[] HEAD_NAMES = {"产品编码"};

	public boolean[] COL_CHECK = new boolean[1];

	// 匹配不包括 ',",<,>,&的特殊字符
	public static final String regula = "[^'\"<>&]*";
	public static final String zhibao = "^\\d+$";


	public String execute(GSBaseForm aForm) throws Exception {
		GSImportExcelForm tGSImportExcelForm = (GSImportExcelForm) aForm;
		FormFile formFile = tGSImportExcelForm.getExcelfile();

		if (formFile != null) {
			loadDataFromExcel(formFile.getInputStream(),aForm);
			}
		return GSBaseConstants.FORWARD_SUCCESS;
	}

	/**
	 * 从Excel中载入格式化数据，数据项之间以分隔符%隔开
	 * 
	 * @param aInputStream
	 * @param aPage
	 * @param aPageSize
	 * @return
	 * @throws Exception
	 */
	public void loadDataFromExcel(InputStream aInputStream,GSBaseForm aForm)
			throws Exception {
		Workbook tExcelWorkbook = null;

		try {
			tExcelWorkbook = Workbook.getWorkbook(aInputStream);

			Sheet tExcelSheet = tExcelWorkbook.getSheet(SHEET_NAME);
			if (tExcelSheet == null) {
				aForm.getRequest().setAttribute("gohistory","true");	
				throw new GSException("批量导入信息失败:文件格式不正确,无法找到：" + SHEET_NAME);
			}
			for (int i = 1; i < tExcelSheet.getRows(); i++) {
				Cell tCells[] = tExcelSheet.getRow(i);
				String tRowText = "";
				int num = tCells.length;
				for (short j = 0; j < num; j++) {
					Cell tExcelCell = tCells[j];
					if (tExcelCell == null) {
						break;
					}
					String tCellValue = tExcelCell.getContents();
					if (tCellValue.length() == 0) {
						tCellValue = " ";
					}
					tRowText += tCellValue + SEP;
				}

				for (int a = num; a < HEAD_NAMES.length; a++) {
					tRowText += " " + SEP;
				}

				// 检查数据是否正确,如果和数据库中不符则将结果添加到末尾,从第二行开始
				
				tRowText = this.checkExecl(tRowText,i, aForm);
				for (int tJ = 0; tJ < COL_CHECK.length; tJ++) {
					if (COL_CHECK[tJ] == false) {
						aForm.getRequest().setAttribute("gohistory","true");	
						throw new GSException(tRowText);
					}
				}
				GSLogWriter.info(tRowText);
			
			}
		} catch (BiffException e) {
			//GSLogWriter.error(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			//GSLogWriter.error(e.getMessage());
			e.printStackTrace();
		}
		finally {
			if (tExcelWorkbook != null)
				tExcelWorkbook.close();
		}
		
	}

	
	
	public String checkExecl(String aRowText,int row,GSBaseForm aForm) throws Exception {
	
		for (int i = 0; i < COL_CHECK.length; i++) {
			COL_CHECK[i] = true;
		}

		String[] tRecorderColumns = aRowText.split(SEP);

		//判断excel字段不能有特殊字符
		for (int i = 0; i < tRecorderColumns.length; i++) {
			if (!RegulaUtil.matchByString(tRecorderColumns[i], regula)) {
				COL_CHECK[i] = false;
				return HEAD_NAMES[0] + tRecorderColumns[0] + ": "
						 + "不能为',\",<,>,&等特殊字符!";
			}
		}
		//判断excel字段不能为空
		if (tRecorderColumns[0].trim().equals("")) {
			COL_CHECK[0] = false;
			return "第"+row+"条记录，"  + HEAD_NAMES[0]
					+ "不能为空！";
		}
		GSProductTiptopStockProcesser ordProcesser = new GSProductTiptopStockProcesser();
		
		//验证在产品编码是否存在
		int isExistStorage = ordProcesser.isExistRow("  select * from T_PRODUCT   where CONCENTRICITY_CODE =  '"+tRecorderColumns[0]+"'");
		if (isExistStorage == 0) {
			COL_CHECK[0] = false;
			return "第"+row+"条记录，"  + HEAD_NAMES[0]
					+ "不存在！";
		}	
		//验证在编码是否存在
		int isExist = ordProcesser.isExistRow("  select * from T_PRODUCT_SHARE_STOAGE   where product_CODE =  '"+tRecorderColumns[0]+"'");
		if (isExist == 0) {
			//新增记录
			GSProductStorageDao psd= new GSProductStorageDao();
		    try {
				boolean success= psd.insertProducStorage(tRecorderColumns[0]);
			} catch (Exception e) {
				e.printStackTrace();
				return "第"+row+"条记录，"  + HEAD_NAMES[0]
				                					+ "插入数据库失败！";
			}
		}
			
		

		aForm.getRequest().setAttribute("message","批量导入信息成功！");
		return "ok";
	}
	

}
